import {Component, OnInit, ViewEncapsulation, ElementRef, OnDestroy} from '@angular/core';
import {ToolsService} from "app/shared/service/tools/tools.service";
import {ActivatedRoute, Params, Router} from "@angular/router";
import {TrainService} from "app/pages/train/train.service";
import {ImageCompress} from "@util/image";
import {AuthService} from "@shared/service/auth/auth.service";


@Component({
  selector: 'remark-detail',
  templateUrl: './remark-detail.component.html',
  styleUrls: ['./remark-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class RemarkDetailComponent implements OnInit, OnDestroy {
  public remark;
  public stateStore = {
    isInitAdd: false, // 是否为新增
    isView: true, // 是否查看状态（非编辑状态）
    isValid: false // 验证是否通过
  };
  public dataStore = {
    avatar: '',
    classId: 0,
    name: '',
    pageTitle: '查看点评',
    identityType: '' // 身份类型
  };
  public teacherParams = {
    orgUserId: '',
    commentId: null, // 点评id
    studentScheduleId: 0, // 课时
    studentId: 0, // 学生id
    content: '', // 点评内容
    filesList: [] // 点评图片
  };

  constructor(private  trainService: TrainService,
              private tools: ToolsService,
              private authService: AuthService,
              private route: ActivatedRoute) {
    this.route.params
      .switchMap((params: Params) => {
        this.dataStore.identityType = params['identityType'];
        return this.route.queryParams;
      }).subscribe((queryParams: Params) => {
        this.dataStore.classId = queryParams['classId'];
        this.dataStore.name = decodeURI(queryParams['name']);
        this.teacherParams.studentId = queryParams['studentId'];
        this.teacherParams.studentScheduleId = queryParams['lessonId'];
        this.teacherParams.commentId = queryParams['remarkId'];
        this.teacherParams.orgUserId = this.authService.getAuthOrgId();
    });
  }

  /**
   * @description 处理文本输入
   * @author ouyqx691
   * @date 2017/12/30
   */
  handleRemarkText(text: string) {
    this.teacherParams.content = text;
    if (text || this.teacherParams.filesList.length > 0) {
      return this.stateStore.isValid = true;
    } else {
      return this.stateStore.isValid = false;
    }
  }


  /**
   * @description 更新点评（增，改）
   * @author ouyqx691
   * @date 2017/12/30
   */
  handleUpdateRemark() {
    if (this.stateStore.isInitAdd) {
      this.addRemark();
    } else {
      this.editRemarkDetail();
    }
  }

  /**
   * @description 添加点评
   * @author ouyqx691
   * @date 2017/12/30
   */
  addRemark() {
    this.trainService.addRemark(this.teacherParams).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.tools.showToast('点评成功');
        this.backToList();
      } else {
        if (res.result === '40109') {
          this.tools.showToast('点评之前需要销课');
        }
      }
    });
  }

  /**
   * @description 查询点评详情(教练)
   * @author ouyqx-691
   * @date 2017-12-27
   */
  getRemarkDetailForTeacher() {
    const param = {
      commentId: this.teacherParams.commentId
    };
    this.stateStore.isValid = true;
    this.trainService.getRemarkDetailForTeacher(param).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.remark = res.data;
        this.dataStore.name = res.data.studentName;
        this.teacherParams.content = res.data.content;
        const pictures = res.data.fileList;
        for (let i = 0; i < pictures.length; i++) {
          this.teacherParams.filesList.push(pictures[i].filePath);
        }
      }
    });
  }

  /**
   * @description 查询点评详情(家长)
   * @author ouyqx-691
   * @date 2017-12-27
   */
  getRemarkDetailForParent() {
    const params = {
      scheduleId: this.teacherParams.studentScheduleId,
      studentId: this.teacherParams.studentId
    };
    this.trainService.getRemarkDetailForParent(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.remark = res.data;
        this.dataStore.name = res.data.teacher.teacharName + ' 点评';
        this.dataStore.avatar = res.data.teacher.imagerUrl;
        this.teacherParams.content = res.data.content;
        const pictures = res.data.commentFiles;
        for (let i = 0; i < pictures.length; i++) {
          this.teacherParams.filesList.push(pictures[i]);
        }
      }
    });
  }

  /**
   * @description 修改点评详情
   * @author ouyqx-691
   * @date 2017-12-30
   */
  editRemarkDetail() {
    this.trainService.updateRemark(this.teacherParams).subscribe((res) => {
      if (res.result === '0' && res.data) {
        this.tools.showToast('编辑成功');
        this.backToList();
      }
    });
  }

  /**
   * @description 图片上传
   * @author ouyqx691
   * @date 2017/12/29
   * @param {Object} e
   */
  addPicture(event) {
    const file = event.target.files[0];
    if (!file && !file.name) return;

    ImageCompress.process(file, 800, 0.5, true)
      .then((url) => {
       this.stateStore.isValid = true;
        this.trainService.upLoadFile(url).subscribe((res) => {
           if (res.result === '0' && res.data) {
             this.stateStore.isValid = true;
             this.teacherParams.filesList.push(res.data);
           }
         });
      })

  }

  /**
   * @description 移除图片
   * @author ouyqx691
   * @date 2017/12/29
   * @param {number} i 图片索引
   */
  removePicture(i: number) {
    this.teacherParams.filesList.splice(i, 1);
    if (this.teacherParams.content || this.teacherParams.filesList.length > 0) {
      return this.stateStore.isValid = true;
    } else {
      return this.stateStore.isValid = false;
    }
  }

  /**
   * @description 删除点评
   * @author ouyqx691
   * @date 2017/12/29
   */
  removeRemark() {
    const text = {
      title: '确认删除该点评?',
      message: '删除后不可恢复',
      cancelBtn: true,
      cancelText: '取消'
    };
    this.tools.present(text).then(result => {
      if (result) {
        const param = {
          commentId: this.teacherParams.commentId
        };
        this.trainService.deleteRemark(param).subscribe(res => {
          this.tools.showToast('删除成功');
          this.backToList();
        });
      }
    });
  }

  resetRemarkState() {
    this.stateStore.isView = false;
    this.dataStore.pageTitle = "编辑点评";
  }

  /**
   * @description 回到列表页面
   * @author ouyqx691
   * @date 2017/12/29
   */
  backToList() {
    setTimeout(() => {
      window.history.back();
    }, 1500);
  }

  ngOnInit() {
    const url = location.href;
    if (this.dataStore.identityType === 'parent') {
      this.getRemarkDetailForParent();
    } else {
      if (!url.includes('remarkId')) {
        this.stateStore.isView = false;
        this.stateStore.isInitAdd = true;
      } else {
        this.getRemarkDetailForTeacher();
      }
    }
  }

  ngOnDestroy() {
  }
}
